package gripper.ftp.info;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import gripper.ftp.FtpServer;
import gripper.ftp.FtpSession;

public class ServerInfo {
	FtpServer ftpServer;
	ConcurrentSkipListSet<FtpSession> sessions;
	long startTime;
	long logCount;
	long tryLogCount;

	public ServerInfo(FtpServer ftpServer, ConcurrentSkipListSet<FtpSession> sessions) {
		this.ftpServer = ftpServer;
		this.sessions = sessions;
		startTime = System.currentTimeMillis();
	}

	public int getSessionCount() {
		return sessions.size();
	}

	public Set<String> activeUsers() {
		Set<String> users = new HashSet<>();
		for (FtpSession fs : sessions) {
			users.add(fs.getUserName());
		}
		return users;
	}

	public int userCount(String user) {
		int count = 0;
		if (user == null) {
			return 0;
		}
		for (FtpSession fs : sessions) {
			if (user.equals(fs.getUserName())) {
				count++;
			}
		}
		return count;
	}

	public Set<String> activeIps() {
		Set<String> ips = new HashSet<>();
		for (FtpSession fs : sessions) {
			String ip = fs.getClientIp();
			if (ip == null) {
				continue;
			}
			ips.add(ip);
		}
		return ips;
	}

	public List<SessionInfo> getSessionInfos() {
		List<SessionInfo> siList = new ArrayList<>(sessions.size());
		for (FtpSession fs : sessions) {
			SessionInfo sessionInfo = new SessionInfo();
			String ip = fs.getClientIp();
			if (ip == null) {
				continue;
			}
			sessionInfo.setIp(ip);
			sessionInfo.setUser(fs.getUserName());
			sessionInfo.setStartTime(fs.getStartTime());
			sessionInfo.setId(fs.getSessionId());
			siList.add(sessionInfo);
		}
		return siList;
	}

	public List<String> getCommandList(long sessionId) {
		for (FtpSession fs : sessions) {
			long sid = fs.getSessionId();
			if (sid != sessionId) {
				continue;
			}
			return fs.getCmdList();
		}
		return null;
	}

	public Date getStartTime() {
		return new Date(startTime);
	}

	public void addLoged() {
		logCount++;
	}

	public long getLogCount() {
		return logCount;
	}
	public void addTryLog() {
		tryLogCount++;
	}

	public long getTryLogCount() {
		return tryLogCount;
	}
}
